// 设置 cookie
export function setCookie(name, value, day) {
  let oDate = new Date()
  oDate.setDate(oDate.getDate() + day)
  if (day) {
    document.cookie = `${name}=${value};expires=${oDate}`
  } else {
    document.cookie = `${name}=${value}`
  }
}

// 获取 cookie
export function getCookie(name) {
  let arr = document.cookie.split('; ')
  for (let i = 0; i < arr.length; i++) {
    let arr2 = arr[i].split('=')
    if (arr2[0] === name) {
      return arr2[1]
    }
  }

  return ''
}

export function removeCookie(name) {
  setCookie(name, 1, -1)
}

export const objToQuery = (json) => {
  let str = ''
  for (let key in json) {
    if (typeof json[key] === 'object') {
      str += `${key}=${JSON.stringify(json[key])}&`
    } else if (json[key] !== null || json[key] !== undefined) {
      str += `${key}=${json[key]}&`
    }
  }

  return str.substring(0, str.length - 1)
}

// 递归查找叶子节点
export const searchLeaves = (arr) => {
  const result = []
  const search = (arr) => {
    for (let item of arr) {
      if (item.children && item.children.length) {
        search(item.children)
      } else {
        result.push(item)
      }
    }
  }
  search(arr)
  return result
}

// 防抖
/**
 *
 * @param {function} func - 防抖的函数
 * @param {number} wait - 等待时间
 * @param {boolean} immediate - 是否立即执行
 */
export function debounce(func, wait, immediate) {
  var timeout, result
  var debounced = function () {
    var context = this
    var args = arguments

    if (timeout) clearTimeout(timeout)
    if (immediate) {
      // 如果已经执行过，不再执行
      var callNow = !timeout
      timeout = setTimeout(function () {
        timeout = null
      }, wait)
      if (callNow) result = func.apply(context, args)
    } else {
      timeout = setTimeout(function () {
        func.apply(context, args)
      }, wait)
    }
    return result
  }

  debounced.cancel = function () {
    clearTimeout(timeout)
    timeout = null
  }

  return debounced
}

/**
 * 格式化时间
 * @param {String|Number} oldDate 传入的日期
 * @param {String|Null} fmt 格式：YYYY-MM-DD hh:mm:ss
 * formatDate(time, 'YYYY-MM-DD hh:mm:ss')
 */
export function formatDate (oldDate, fmt) {
  let date = new Date()
  if (oldDate || typeof oldDate === 'string' || typeof oldDate === 'number') {
    date = new Date(oldDate)
  }

  const len2 = (num) => {
    return num < 10 ? '0' + num : '' + num
  }

  const obj = {
    YYYY: date.getFullYear(),
    YY: (date.getFullYear() + '').substring(2, 4) * 1,
    MM: len2(date.getMonth() + 1),
    DD: len2(date.getDate()),
    hh: len2(date.getHours()),
    mm: len2(date.getMinutes()),
    ss: len2(date.getSeconds())
  }

  if (fmt) {
    if (/YYYY/.test(fmt)) {
      fmt = fmt.replace('YYYY', obj.YYYY)
    } else {
      fmt = fmt.replace('YY', obj.YY)
    }
    fmt = fmt.replace('MM', obj.MM)
    fmt = fmt.replace('DD', obj.DD)
    fmt = fmt.replace('hh', obj.hh)
    fmt = fmt.replace('hh', obj.hh)
    fmt = fmt.replace('mm', obj.mm)
    fmt = fmt.replace('mm', obj.mm)
    fmt = fmt.replace('ss', obj.ss)
  } else {
    fmt = `${obj.YYYY}-${obj.MM}-${obj.DD}`
  }
  return fmt
}
